//4.对数组进行拦截

const arrayProto = Array.prototype;
const arrayMethods = Object.create(arrayProto);
[
    'push',
    'pop',
    'shift',
    'unshift',
    'splice',
    'sort',
    'reverse'
].forEach(function (method) {
    // 缓存原始方法
    const original = arrayProto[method];
    Object.defineProperty(arrayMethods, method, {
        value: function mutator(...args) {
            console.log('修改数组---')
            return original.apply(this, args);
        },
        enumerable:false,
        writable:true,
        configurable:true
    }
    )
});

function observer(obj) {
    if (Array.isArray(obj)) {//4.对数组进行拦截
        obj.__proto__ = arrayMethods;
    } else {
        Object.keys(obj).forEach((key) => {
            defineReactive(obj, key, obj[key]);
        });
    }
}

function defineReactive(data, key, val) {
    if (typeof val === 'object') { //1.所有属性都响应式
        observer(val);
    }
    Object.defineProperty(data, key, {
        enumerable: true,
        configurable: true,
        get: function () {
            console.log('get--------', val);
            return val;
        },
        set: function (newVal) {
            if (val === newVal) {
                return;
            }
            console.log('set--------', newVal);
            if (typeof newVal === 'object') {// 2.修改的值是对象
                observer(newVal);
            }
            val = newVal;
        }
    });
}

// 3.新增的属性也可以响应式
function $set(obj, key, val) {
    defineReactive(obj, key, val);
}






